package com.qf.mybatis03.entity;

import cn.hutool.core.util.RandomUtil;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Book implements Serializable {
    private Integer id;
    private String name;
    private String author;
    private String publish;
    private Integer sort;

    //产生一本新的随机属性的book
    public static Book randomBook(){
        Book book = new Book();
        //产生随机的书名 借助hutool工具类
        String name = RandomUtil.randomString(20);
        //产生随机的作者名
        String author = RandomUtil.randomString(10);
        //产生随机的出版社
        String publish = RandomUtil.randomString(25);
        //产生随机的排名
        int sort = RandomUtil.randomInt(0, 100000);

        book.setName(name);
        book.setAuthor(author);
        book.setPublish(publish);
        book.setSort(sort);

        return book;
    }

    //产生多本新的随机属性的book 参数传多少就产生多少本书
    public static List<Book> randomBooks(Integer size){
        List<Book> books = new ArrayList<>();
        for (int i = 0; i < size; i++) {
            books.add(randomBook());
        }
        return books;
    }

    //将book对象转换成 csv字符串  eg:f78af79dsf9asf,fsf7asfa8sf,fashjasfjhasfasfkasf,7875457
    public String toCSVString(){
        return this.name+","+this.author+","+this.publish+","+this.sort;
    }

    //把逗号分隔的字符串转换为book对象
    public static Book csvToBook(String csv){
        String[] split = csv.split(",");
        Book book = new Book();

        book.setName(split[0]);
        book.setAuthor(split[1]);
        book.setPublish(split[2]);
        book.setSort(Integer.valueOf(split[3]));

        return book;
    }
}
